package com.pospi.pospihold.ui.cash_ui;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.pospi.pospihold.App;
import com.pospi.pospihold.R;
import com.pospi.pospihold.adapter.PointSelectLeftAdapter;
import com.pospi.pospihold.adapter.YsAdapter;
import com.pospi.pospihold.dao.GoodsDao;
import com.pospi.pospihold.dao.OrderDao;
import com.pospi.pospihold.dto.GoodsDto;
import com.pospi.pospihold.dto.MenuDto;
import com.pospi.pospihold.dto.ModifiedDto;
import com.pospi.pospihold.dto.ModifiedGroupDto;
import com.pospi.pospihold.dto.OrderDto;
import com.pospi.pospihold.dto.PrintBeen;
import com.pospi.pospihold.dto.RestOrderBeen;
import com.pospi.pospihold.dto.TableDto;
import com.pospi.pospihold.greendao.PrintBeenDao;
import com.pospi.pospihold.http.LoadServer;
import com.pospi.pospihold.http.MaxNO;
import com.pospi.pospihold.http.UploadData;
import com.pospi.pospihold.sprint.Communication;
import com.pospi.pospihold.sprint.PrinterFunctions;
import com.pospi.pospihold.sprint.StarPrintHelper;
import com.pospi.pospihold.ui.pay_ui.PayActivity;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.ui.pay_ui.PayNewActivity;
import com.pospi.pospihold.ui.pay_ui.UnionConfig;
import com.pospi.pospihold.util.Api;
import com.pospi.pospihold.util.Constant;
import com.pospi.pospihold.util.DoubleSave;
import com.pospi.pospihold.util.DownUtil;
import com.pospi.pospihold.util.GetData;
import com.pospi.pospihold.util.SaveMenuInfo;
import com.pospi.pospihold.util.SaveOrderInfo;
import com.pospi.pospihold.util.TurnSize;
import com.pospi.pospihold.view.PointSelectUtil.PinnedHeaderListView;
import com.pospi.pospihold.view.PointSelectUtil.TestSectionedAdapter;
import com.starmicronics.starioextension.StarIoExt;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PointSelectActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.order_detail)
    ImageView orderDetail;
    @Bind(R.id.what_money)
    TextView tvMoney;
    @Bind(R.id.settle)
    TextView settle;
    @Bind(R.id.ll_bottom)
    LinearLayout llBottom;
    @Bind(R.id.left_listview)
    ListView left_listView;
    @Bind(R.id.pinnedListView)
    PinnedHeaderListView right_listview;
    @Bind(R.id.retain)
    TextView retain;
    @Bind(R.id.cart_anim_icon)
    ImageView mAnimImageView;
    @Bind(R.id.parent)
    LinearLayout parent;
    @Bind(R.id.tv_num)
    TextView tv_num;
    private Animation mAnimation;
    private TestSectionedAdapter sectionedAdapter;
    private List<GoodsDto> goodinfos = new ArrayList<>();
    private List<List<GoodsDto>> lists;
    private PointSelectGoodsDetailAdapter adapter;
    private double totalMoney = 0;
    private int num;
    private int scrollNum;

    private int maxNO;
    private OrderDto orderDto;
    private List<ModifiedDto> modifiedDtos;
    private List<ModifiedGroupDto> modifiedGroupDtos;
    private PopupWindow popupWindow;
    private TableDto tableDto;
    private RestOrderBeen orderBeen;
    private List<byte[]> bytes;
    private String tableMsg = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_point_select);
        setTitle("点选收款");
        ButterKnife.bind(this);
        setMenuText("+ 添加餐桌");
        setMenuImage(R.drawable.tag_bg);
        modifiedDtos = new Gson().fromJson(SPHelper.getInstance().getString(Api.YS), new TypeToken<List<ModifiedDto>>() {
        }.getType());
        modifiedGroupDtos = new Gson().fromJson(SPHelper.getInstance().getString(Api.YSZ), new TypeToken<List<ModifiedGroupDto>>() {
        }.getType());
        addData();
        init();

    }

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        startActivity(TableActivity.class);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        tableDto = (TableDto) intent.getSerializableExtra("data");
        addTable();
        String mark = intent.getStringExtra("mark");
        if (mark != null && mark.equals("pay")) {
            goodinfos.clear();
            setShoppings();
            clearTable();
        }
    }

    public void init() {
        orderBeen = (RestOrderBeen) getIntent().getSerializableExtra("order");
        if (orderBeen != null) {
            setMenuText(orderBeen.getTableNo());
            tableMsg = orderBeen.getTableNo();
            List<GoodsDto> goodsDtos = SaveOrderInfo.changeToList(orderBeen.getMsg());
            for (GoodsDto dto : goodsDtos) {
                dto.setPrintType("1");
            }
            goodinfos.addAll(goodsDtos);
        } else {
            maxNO = MaxNO.getMaxNo(getApplicationContext());
            goodinfos = new ArrayList<>();
        }

        setShoppings();
    }

    public void addData() {
        lists = new ArrayList<>();
        String menuInfo = getSharedPreferences("MenuDto_json", MODE_PRIVATE).getString("json", "");
        List<MenuDto> menuDtos = SaveMenuInfo.changeToList(menuInfo);
        List<String> titles = new ArrayList<>();
        List<String> code = new ArrayList<>();
        for (int i = 0; i < menuDtos.size(); i++) {
            titles.add(menuDtos.get(i).getName());
            code.add(menuDtos.get(i).getSid());
        }
        GoodsDao dao = new GoodsDao(getApplicationContext());
        for (int i = 0; i < titles.size(); i++) {
            List<GoodsDto> goodsBeens = dao.findSelectPointGoods(code.get(i));
            lists.add(goodsBeens);
        }

        sectionedAdapter = new TestSectionedAdapter(this, titles, lists);
        right_listview.setAdapter(sectionedAdapter);

        PointSelectLeftAdapter leftAdapter = new PointSelectLeftAdapter(getApplicationContext(), titles);
        left_listView.setAdapter(leftAdapter);



    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    Toast.makeText(PointSelectActivity.this, "落单成功", Toast.LENGTH_SHORT).show();
                    startPrint();
                    break;
                case 2:
                    close();
                    new AlertDialog.Builder(PointSelectActivity.this)
                            .setTitle("提示")
                            .setMessage("落单失败，请重试")
                            .setPositiveButton("重试", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            })
                            .setNegativeButton("取消", null).show();
                    break;
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStart() {
        super.onStart();
        mAnimation = AnimationUtils.loadAnimation(PointSelectActivity.this, R.anim.cart_anim);
        mAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mAnimImageView.setVisibility(View.INVISIBLE);
            }
        });
        left_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position,
                                    long arg3) {
                int rightSection = 0;
                for (int i = 0; i < position; i++) {
                    rightSection += sectionedAdapter.getCountForSection(i) + 1;
                }
                right_listview.setSelection(rightSection);
            }
        });

        left_listView.setOnScrollListener(new ListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                scrollNum = firstVisibleItem;
            }
        });

        right_listview.setOnItemClickListener(new PinnedHeaderListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int section, int position, long id) {

                    GoodsDto goodsDto = lists.get(section).get(position);
                    if (goodsDto.getGroup_sid() != null && !goodsDto.getGroup_sid().isEmpty()) {
                        String[] list = goodsDto.getGroup_sid().split(",");
                        List<ModifiedGroupDto> dtoList = new ArrayList<ModifiedGroupDto>();
                        for (String s : list) {
                            for (ModifiedGroupDto groupDto : modifiedGroupDtos) {
                                if (s.equals(groupDto.getSid())) {
                                    dtoList.add(groupDto);
                                }
                            }
                        }
                        showYs(dtoList ,goodsDto);
                    } else {
                        addGoods(goodsDto);
                    }

            }


            @Override
            public void onSectionClick(AdapterView<?> adapterView, View view, int section, long id) {
            }
        });

        right_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                int onScrollItem = sectionedAdapter.getSectionForPosition(firstVisibleItem);
                for (int i = 0; i < left_listView.getChildCount() + scrollNum; i++) {
                    if (i == onScrollItem) {
                        if (i - scrollNum > -1) {
                            left_listView.getChildAt(i - scrollNum)
                                    .setBackgroundColor(getResources().getColor(R.color.white));
                            left_listView.setSelection(onScrollItem);
                        }
                    } else {
                        try {
                            left_listView.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.colorBackground));
                        } catch (Exception e) {
                        }
                    }
                }
            }
        });
    }
    public void showAnimation() {
        mAnimImageView.startAnimation(mAnimation);
        mAnimImageView.setVisibility(View.VISIBLE);
    }

    private void addGoods(GoodsDto dto) {
        showAnimation();

        if (goodinfos.contains(dto)) {
            for (int i = 0; i < goodinfos.size(); i++) {
                if (goodinfos.get(i).getSid().equals(dto.getSid())) {
                    Log.i("size", goodinfos.get(i).getNum() + "");
                    goodinfos.get(i).setNum(goodinfos.get(i).getNum() + 1);
                    Log.i("size", goodinfos.get(i).getNum() + "");
                }
            }
        } else {
            goodinfos.add(dto);
        }
        setShoppings();

    }
    private void setShoppings(){
        totalMoney = 0;
        num = 0;
        for (int i = 0; i < goodinfos.size(); i++) {
            totalMoney += goodinfos.get(i).getPrice() * goodinfos.get(i).getNum();
            num+=goodinfos.get(i).getNum();
        }
        tvMoney.setText(String.valueOf(DoubleSave.doubleSaveTwo(totalMoney)));
        if (num != 0) {
            tv_num.setVisibility(View.VISIBLE);
            tv_num.setText(String.valueOf(num));
        } else {
            tv_num.setVisibility(View.INVISIBLE);
        }


    }

    @OnClick({R.id.order_detail, R.id.settle, R.id.retain})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.order_detail:
                LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                View contentView = mLayoutInflater.inflate(R.layout.pointselect_detail, null);
                // R.layout.pop为PopupWindow 的布局文件
                PopupWindow pop = new PopupWindow(contentView, ActionBar.LayoutParams.MATCH_PARENT, TurnSize.dip2px(getApplicationContext(), 300));
                pop.setBackgroundDrawable(new BitmapDrawable());
                // 指定 PopupWindow 的背景
                pop.setFocusable(true);
                //指定PopupWindow显示在你指定的view下

                int[] location = new int[2];
                llBottom.getLocationOnScreen(location);
                pop.showAtLocation(llBottom, Gravity.NO_GRAVITY, location[0], location[1] - pop.getHeight());

                ListView info = (ListView) contentView.findViewById(R.id.lv_detail);
                adapter = new PointSelectGoodsDetailAdapter(getApplicationContext(), goodinfos);
                info.setAdapter(adapter);
//                Constant.fixListViewHeight(info);
                RelativeLayout ll = (RelativeLayout) contentView.findViewById(R.id.delete);
                ll.setOnClickListener(this);
                break;
            case R.id.settle:
                UnionConfig.accessToken();
                if (goodinfos.isEmpty()) {
                    showToast("请添加商品");
                } else {
                    SaveOrderInfo.saveAsJson(getApplicationContext(), goodinfos);
                    Intent intent = new Intent(PointSelectActivity.this, PayNewActivity.class);
                    intent.putExtra("data", tvMoney.getText().toString());
                    intent.putExtra("remark", "PointSelectActivity");
                    startActivity(intent);
                }
                break;
            case R.id.delete:
                clearTable();

                if (goodinfos.isEmpty()) {
                    showToast("商品为空");
                } else {
                    showDeleteDialog();
                }
                break;
            case R.id.retain:
                if (goodinfos.isEmpty()) {
                    showToast("请添加商品");
                } else {
                    final AlertDialog deleteDialog = new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("确定挂单？")
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    addRestOrderinfo();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .create();
                    deleteDialog.show();
                }
                break;
        }
    }

    public void addRestOrderinfo() {
        String shopId = getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", "");
        OrderDto orderDto = new OrderDto();
        orderDto.setOrder_info(SaveOrderInfo.changeGoodDtoToJson(goodinfos));//存储的该订单的商品的信息
        orderDto.setPayway(null);
        orderDto.setTime(GetData.getYYMMDDTime());
        orderDto.setSs_money(0.00);
        orderDto.setYs_money(DoubleSave.doubleSaveTwo(Double.parseDouble(tvMoney.getText().toString())));
        orderDto.setZl_money(0.00);
        orderDto.setCashiername(App.getCashierMsgDto().getName());
        orderDto.setCashiernumber(App.getCashierMsgDto().getNumber());
        orderDto.setShop_id(shopId);
        orderDto.setOrderType(Constant.ORDERTYPE_GD);
        orderDto.setMaxNo(maxNO);
        orderDto.setCheckoutTime(GetData.getDataTime());
        orderDto.setDetailTime(GetData.getHHmmssTimet());
        orderDto.setHasReturnGoods(Constant.hasReturnGoods_No);
        orderDto.setOut_trade_no(null);
        orderDto.setTable(tableMsg.isEmpty() ? "无" : tableMsg);
        //当挂单的时候该数据用于保存是哪个界面进行的挂单操作
        orderDto.setPayReturn(RestOrderActivity.REST_Point);
        orderDto.setIfFinishOrder(Constant.NO);
        /**
         * 给数据库里面添加一条记录
         */
        showDialog();

        LoadServer.getConnect(this, Api.REST_ORDER, UploadData.getParams(this,orderDto), new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("data", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    Log.i("data", object.getString("Message"));
                    if (object.getString("Result").equals("1")) {
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = 2;
                    handler.sendMessage(message);
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 2;
                handler.sendMessage(message);
            }
        });

//        new OrderDao(getApplicationContext()).addOrder(orderDto);


    }

    private void startPrint(){
        bytes = new ArrayList<>();
        for (GoodsDto dto : goodinfos) {
            dto.setTableMsg(getMenuText());
            if (!"1".equals(dto.getPrintType())) {
                ImageTask mImageTask = new ImageTask();
                mImageTask.execute(dto);
            }

        }
        goodinfos.clear();
//        adapter.notifyDataSetChanged();
        setShoppings();
        clearTable();



    }

    private class ImageTask extends AsyncTask<GoodsDto, Integer, Bitmap> {
        private String ip  = "";
        @Override
        protected Bitmap doInBackground(GoodsDto... params) {
            PrintBeen been = App.getInstance().getDaoSession().getPrintBeenDao().queryBuilder().
                    where(PrintBeenDao.Properties.Sid.eq(params[0].getMainPrinterSid())).unique();
            if (been != null) {
                ip = been.getIp();
            }

            return StarPrintHelper.creatImage(params[0], PointSelectActivity.this);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            byte[] commands;
            if (bitmap != null) {
                commands = PrinterFunctions.createRasterData(StarIoExt.Emulation.StarPRNT, bitmap, 576, true);
            } else {
                commands = new byte[0];
            }
            if (ip != null && !ip.isEmpty()) {

                print(commands, ip);
            }

            Log.i("img", "生成完成"+ip);

        }
    }

    private void print(byte[] bytes,String ip) {
        Communication.sendCommands(this,bytes,"TCP:"+ip,"",10000,this,mCallback);
    }

    private static final int PRINT_SUCESS = 100;
    private static final int PRINT_FAILED = 101;
    private int printCode;
    private boolean open;
    private final Communication.SendCallback mCallback = new Communication.SendCallback() {
        @Override
        public void onStatus(boolean result, Communication.Result communicateResult) {

            String msg;

            switch (communicateResult) {
                case Success:
                    printCode = PRINT_SUCESS;
                    msg = "Success!";
                    break;
                case ErrorOpenPort:
                    printCode = PRINT_FAILED;
                    msg = "Fail to openPort";
                    break;
                case ErrorBeginCheckedBlock:
                    printCode = PRINT_FAILED;
                    msg = "Printer is offline (beginCheckedBlock)";
                    break;
                case ErrorEndCheckedBlock:
                    printCode = PRINT_FAILED;
                    msg = "Printer is offline (endCheckedBlock)";
                    break;
                case ErrorReadPort:
                    printCode = PRINT_FAILED;
                    msg = "Read port error (readPort)";
                    break;
                case ErrorWritePort:
                    printCode = PRINT_FAILED;
                    msg = "Write port error (writePort)";
                    break;
                default:
                    printCode = PRINT_FAILED;
                    msg = "Unknown error";
                    break;
            }
            Log.i("print", msg);

            if (printCode == PRINT_FAILED) {
                Toast.makeText(PointSelectActivity.this, msg+"打印失败", Toast.LENGTH_SHORT).show();
//                new AlertDialog.Builder(PointSelectActivity.this)
//                        .setMessage(msg)
//                        .setTitle("打印失败")
//                        .setPositiveButton("重新打印", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//
//                            }
//                        }).show();
            }

        }
    };

    public void showDeleteDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("销毁提示")
                .setMessage("确定销毁该订单吗?")
                .setPositiveButton("销毁", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        goodinfos.clear();
                        setShoppings();
                        adapter.notifyDataSetChanged();
                        totalMoney = 0;
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create();
        dialog.show();
    }
    private void clearTable(){
        setMenuText("+ 添加餐桌");
        tableMsg = "";
        if (tableDto != null) {
            tableDto = null;
        }
    }
    private void addTable(){

        if (tableDto != null) {
            setMenuText(tableDto.gettArea() + "-" + tableDto.getTablesName());
            tableMsg = tableDto.gettArea() + "-" + tableDto.getTablesName();
        }
    }

    class PointSelectGoodsDetailAdapter extends BaseAdapter {
        private Context context;
        private List<GoodsDto> goodsDtos;

        public PointSelectGoodsDetailAdapter(Context context, List<GoodsDto> goodsDtos) {
            this.context = context;
            this.goodsDtos = goodsDtos;
        }

        @Override
        public int getCount() {
            return goodsDtos.size();
        }

        @Override
        public Object getItem(int position) {
            return goodsDtos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.pointselect_detail_item, null);
                holder = new ViewHolder();
                holder.name = (TextView) convertView.findViewById(R.id.goods_name);
                holder.price = (TextView) convertView.findViewById(R.id.goods_price);
                holder.num = (TextView) convertView.findViewById(R.id.goods_num);
                holder.add = (ImageView) convertView.findViewById(R.id.add_num);
                holder.js = (ImageView) convertView.findViewById(R.id.substract_goods);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.name.setText(goodsDtos.get(position).getName());
            holder.num.setText(String.valueOf(goodsDtos.get(position).getNum()));

            final double goodsPrice = goodinfos.get(position).getPrice();
            holder.price.setText(String.valueOf(goodsPrice));

            holder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goodsDtos.get(position).setNum(goodsDtos.get(position).getNum() + 1);
                    holder.num.setText(String.valueOf(goodsDtos.get(position).getNum()));
                    totalMoney += goodsPrice;
                    setShoppings();
                }
            });
            holder.js.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (goodsDtos.get(position).getNum() > 1) {
                        goodsDtos.get(position).setNum(goodsDtos.get(position).getNum() - 1);
                        holder.num.setText(String.valueOf(goodsDtos.get(position).getNum()));
                    } else {
                        goodsDtos.remove(position);
                    }
                    totalMoney -= goodsPrice;
                    adapter.notifyDataSetChanged();
                    setShoppings();
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView name;
            TextView price;
            TextView num;
            ImageView add;
            ImageView js;
        }
    }

    private void showYs(List<ModifiedGroupDto> groupDtos , final GoodsDto goodsDto){
        goodsDto.setLabel("");

        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_ys, null);
        LinearLayout ll_label = (LinearLayout) contentView.findViewById(R.id.ll_label);
        TextView tv_price = (TextView) contentView.findViewById(R.id.tv_price);
        TextView tv_title = (TextView) contentView.findViewById(R.id.tv_title);
        Button bt_add = (Button) contentView.findViewById(R.id.bt_add);
        ImageView iv_close = (ImageView) contentView.findViewById(R.id.iv_close);

        tv_title.setText(goodsDto.getName());
        tv_price.setText("￥"+goodsDto.getPrice());
        final List<List<ModifiedDto>> list = new ArrayList<>();
        for (ModifiedGroupDto groupDto : groupDtos) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_label, null);
            final TagFlowLayout flowLayout = (TagFlowLayout) view.findViewById(R.id.id_flowlayout);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            final List<String> strings = getlabel(groupDto.getSid());
            final List<ModifiedDto> modifiedDtos = getModi(groupDto.getSid());
            list.add(modifiedDtos);
            tv_name.setText(groupDto.getName()+":");
            flowLayout.setAdapter(new TagAdapter<String>(strings)
            {

                @Override
                public View getView(FlowLayout parent, int position, String s)
                {
                    TextView tv = (TextView) LayoutInflater.from(PointSelectActivity.this).inflate(R.layout.lable_item,
                            flowLayout, false);

                    tv.setText(s);
                    return tv;
                }

                @Override
                public void onSelected(int position, View view) {
                    super.onSelected(position, view);
                    modifiedDtos.get(position).setStatus(true);
                }

                @Override
                public void unSelected(int position, View view) {
                    super.unSelected(position, view);
                    modifiedDtos.get(position).setStatus(false);
                }
            });

            ll_label.addView(view);

        }
        bt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StringBuilder builder = new StringBuilder();
                for (List<ModifiedDto> dtoList : list) {
                    for (ModifiedDto dto : dtoList) {
                        if (dto.isStatus()) {
                            builder.append(dto.getName()+" ");
                        }
                    }
                }
                Log.i("lable", builder.toString());
                goodsDto.setLabel(builder.toString());
                addGoods(goodsDto);
                popupWindow.dismiss();

            }
        });
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        backgroundAlpaha(this, 0.5f);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpaha(PointSelectActivity.this, 1.0f);
            }
        });
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
    }
    private List<ModifiedDto> getModi(String id) {
        List<ModifiedDto> strings = new ArrayList<>();
        for (ModifiedDto dto : modifiedDtos) {
            dto.setStatus(false);
            if (dto.getGroupSid().equals(id)) {
                strings.add(dto);
            }
        }
        return strings;
    }
    private List<String> getlabel(String id) {
        List<String> strings = new ArrayList<>();
        for (ModifiedDto dto : modifiedDtos) {
            if (dto.getGroupSid().equals(id)) {
                strings.add(dto.getName());
            }
        }
        return strings;
    }

}